package com.example.demo.repo;

import com.example.demo.repo.model.Bill;
import com.example.demo.repo.model.Order;
import org.springframework.stereotype.Repository;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

// 这里用map模拟库存，不走DB
@Repository
public class DBRepo implements Repo {

    private Map<Long, Order> orderMap = new ConcurrentHashMap<>();
    private Map<Long, Bill> billMap = new ConcurrentHashMap<>();

    @Override
    public void putOrder(Order order) {
        orderMap.put(order.getOrderId(), order);
    }

    @Override
    public Optional<Order> getOrder(Long orderId) {
        return Optional.ofNullable(orderMap.get(orderId));
    }

    @Override
    public List<Order> getAllOrders() {
        return new ArrayList<>(orderMap.values());
    }

    @Override
    public void putBill(Bill bill) {
        billMap.put(bill.getBillId(), bill);
    }

    @Override
    public Optional<Bill> getBill(Long billId) {
        return Optional.ofNullable(billMap.get(billId));
    }


    @PostConstruct
    public void init() {
        executorService = Executors.newScheduledThreadPool(1);
        executorService.scheduleAtFixedRate(() -> dump(), 0, 10, TimeUnit.SECONDS);
    }

    private ScheduledExecutorService executorService;

    public void dump() {
        System.out.println(orderMap);
        System.out.println(billMap);
    }

}
